<template>
  <Modal
    v-model="dialogVisible"
    :title="modalTitle"
    width="65%"
    @on-cancel="handleCloseDialog"
  >
    <div>
      <Form
        ref="formData"
        :model="formData"
        :rules="formDataRules"
        :label-width="140"
        :disabled="isView"
      >
        <Row>
          <Col span="18" offset="2">
            <FormItem label="资质名称" prop="qualificationName">
              <Input
                v-model="formData.qualificationName"
                placeholder="请输入资质名称"
                maxlength="20"
                show-word-limit
              ></Input>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="检验类型" prop="qualificationName">
              <RadioGroup v-model="formData.examineCate">
                <Radio label="1">全检</Radio>
                <Radio label="2">抽检</Radio>
                <Radio label="3">通用</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="是否原件" prop="qualificationName">
              <RadioGroup v-model="formData.original">
                <Radio label="1">是</Radio>
                <Radio label="2">否</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="资质类型" prop="qualificationName">
              <RadioGroup
                v-model="formData.qualificationCate"
                style="width: 200px"
                @on-change="radioChange($event)"
              >
                <Radio
                  :label="item.quaTypeNo"
                  :value="item.quaTypeNo"
                  v-for="(item, index) in quaTypeProductData"
                  :key="index"
                >
                  <span>{{ item.quaTypeName }}</span>
                </Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="供应商" prop="qualificationName">
              <Input
                v-model="formData.supplyName"
                style="width: 200px"
                placeholder="请输入供应商"
                search
                suffix="ios-search"
                @on-search="searcheSupply"
                readonly
              />
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="使用区域" prop="qualificationName">
              {{ formData.appliedAreaName }}
              <Button
                @click="salableAreaHandle"
                icon="ios-add"
                type="dashed"
                size="small"
                >选择区域</Button
              >
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="过期时间" prop="qualificationName">
              <DatePicker
                type="date"
                v-model="formData.expireDate"
                format="yyyy-MM-dd HH:mm:ss"
                @on-change="changeStatTime($event)"
                placeholder="请选择时间"
                :options="startTimeOption"
              />
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <!-- 相关方法内容在fileMixins中 -->
            <FormItem label="资质文件类型" prop="qualificationName">
              <RadioGroup
                v-model="qualificationFileType"
                @on-change="handleChangeTypeByQuaFile"
              >
                <Radio label="1">附件</Radio>
                <Radio label="2">图片</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <!-- isFileTypeByPdf在fileMixins中 -->
          <Col span="18" offset="2" v-show="isFileTypeByPdf()">
            <FormItem label="上传附件" prop="qualificationName">
              <Upload
                ref="uploadFile"
                action="/sysback/fileserver/uploadForQualification"
                name="myfile"
                :format="['pdf']"
                :accept="'.pdf'"
                :default-file-list="uploadFileList"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                :before-upload="handleBeforeFileUpload"
                :on-preview="onPreView"
                :on-format-error="formatError"
                :on-remove="handleRemoveFile"
                :max-size="1024 * 100"
                :on-exceeded-size="handleMaxSize"
                :disabled="uploadBtnLoading"
              >
                <Button :loading="uploadBtnLoading" icon="ios-cloud-upload-outline">点击上传</Button>
              </Upload>
            </FormItem>
          </Col>
          <!-- isFileTypeByImage在fileMixins中 -->
          <Col span="18" offset="2" v-show="isFileTypeByImage()">
            <FormItem label="上传图片" prop="qualificationName">
              <UploadImg
                :isMultiple="true"
                :readOnly="isView"
                class="ivu-mr qw-disflex"
                :defaultList="defaultList"
                uploadForQualification="sysback/fileserver/uploadForQualification"
                :mr="16"
                :maxSize="2048"
                :maxLen="10"
                :format="['jpg', 'jpeg', 'png']"
                previewModalWidth="80%"
                @handleChangeImage="changeImageKey"
              >
              </UploadImg>
              <p>提示: 上传图片大小不能超过2048K,尺寸750px*360px</p>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <!-- 相关方法内容在fileMixins中 -->
            <Form :label-width="140">
              <FormItem label="一键下载">
                <Button
                  type="dashed"
                  size="small"
                  icon="md-download"
                  :loading="btnLoading.download"
                  @click="handleDownloadFiles"
                >下载</Button>
              </FormItem>
            </Form>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="介绍">
              <Input
                v-model="formData.note"
                type="textarea"
                maxlength="50"
                show-word-limit
                :autosize="{ minRows: 2, maxRows: 5 }"
                placeholder="请输入介绍内容"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Modal v-model="modal1" title="选择区域">
        <Tree
          ref="cityTree"
          :data="treeCityData"
          show-checkbox
          multiple
          @on-check-change="checkCityChange"
        />
      </Modal>
      <Modal v-model="supplierMainModel" width="1000" title="供应商列表">
        <Card dis-hover>
          <Row type="flex" justify="start" align="bottom">
            <Col style="margin-right: 40px">
              <span style="margin-right: 10px">供应商名称</span>
              <Input
                style="width: auto"
                v-model="supplierName"
                placeholder="请输入供应商名称"
              ></Input>
            </Col>
            <Col style="margin-right: 40px">
              <span style="margin-right: 10px">供应商编号</span>
              <Input
                style="width: auto"
                v-model="supplierNo"
                placeholder="请输入供应商编号"
              ></Input>
            </Col>
            <Col>
              <Button
                type="primary"
                style="margin-right: 10px"
                @click="searchBySupplierFun('1')"
                >查询</Button
              >
              <Button @click="searchBySupplierFun('0')">清空</Button>
            </Col>
          </Row>
        </Card>
        <Card dis-hover>
          <div>
            <div class="mt-10">
              <Table
                ref="selection"
                border
                :columns="supplierMainCol"
                :data="supplierMainData"
                @on-select="handleTablaeSelect($event)"
                @on-select-all="handleSelectAll($event)"
                @on-select-all-cancel="handleSelectAllCancel($event)"
              >
                <template slot-scope="{ row }" slot="action">
                  <Button type="primary" @click="selectSupplier(row)"
                    >选择</Button
                  >
                </template>
              </Table>
            </div>
            <div style="display: flex; justify-content: center">
              <Page
                :total="totalNum"
                show-total
                show-elevator
                show-sizer
                transfer
                @on-change="changePage"
                @on-page-size-change="changePageSize"
              />
            </div>
          </div>
        </Card>
      </Modal>
    </div>
    <div v-show="!isView" slot="footer">
      <Button type="text" @click="handleCloseDialog">取消</Button>
      <Button type="primary" :loading="rLoading" @click="handleOk">确定</Button>
    </div>
  </Modal>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { cityTreeDataUtils } from '@/assets/js/commonUtils';
import UploadImg from '@/components/common/upload'; // 上传组件
import { getBtnsId } from '@/libs/btnsPermission';
import BasicDialog from '@/components/BasicDialog';
import fileMixins from './mixins/file';
export default {
  mixins: [fileMixins],
  components: { UploadImg, BasicDialog },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    uuid: {
      type: String,
      required: true
    },
    // 是否只查看
    isView: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      uploadBtnLoading: false,
      startTimeOption: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      supplierName: '', // 供应商名称搜索用
      supplierNo: '', // 供应商编码搜索用
      supplierMainModel: false,
      totalPage: 0,
      pageShow: 10,
      nowPage: 1,
      supplierMainCol: [
        {
          title: '供应商名称',
          key: 'supplierName',
          minWidth: 150
        },
        {
          title: '供应商编码',
          key: 'supplierNo',
          minWidth: 150
        },
        {
          title: '供应商状态',
          key: 'supplierStatusName'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          minWidth: 150
        }
      ],
      supplierMainData: [],
      quaTypeProductData: [],
      totalNum: 0,
      upLoadData: {
        categoryUuid: '111000'
      },
      fileCon: {
        type: 'select', // 上传控件的类型，可选值为 select（点击选择），drag（支持拖拽）
        showUploadList: true,
        multiple: false, // 是否支持多选文件
        format: ['jpg', 'jpeg', 'png'], // 支持的文件类型
        maxSize: 2048, // 文件大小限制，单位 kb Number
        maxLen: '3' // 文件数量限制
      },
      fileData: [],
      // supplierNo: '',
      imageUrl: '',
      uploadList: [],
      uploadFileList: [],
      rLoading: false,
      defaultList: [],
      // 请求接口地址
      requestApi: {
        // 视情况自定义
        // 获取商品资质管理列表数据
        baseUpdate: {
          url: '/sysback/qualification/updateQuaInfo', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 获取商品资质管理数据
        baseGetByUuid: {
          url: '/sysback/qualification/getQuaByUuid', // 接口地址
          type: 'get' // 接口请求类型
        },
        // 主推城市
        getCityTree: {
          url: '/sysback/addsingleproduct/basicinfo/getCityTree',
          type: 'post'
        },
        // 获取供应商列表
        getPagerSupplierMainInfo: {
          url: '/sysback/supplier/maininfo/list/getPotentialOrQualifiedSupplierPager',
          type: 'post'
        },
        // 查询商品资质类型
        quaTypeProductList: {
          url: '/sysback/quatype/quaTypeProductList',
          type: 'post'
        }
      },
      modal1: false,
      treeCityData: [],
      brandList: [],
      salableAreaData: [],
      areaNames: [],
      cityUuids: [],
      productDetailImages: [], // 图片回显
      formData: {
        qualificationName: '', // 资质名称
        examineCate: '1', // 检验类型 默认 1 全检
        original: '1', // 是否原件
        qualificationCate: '1', // 资质类型
        qualificationCateName: '', // 资质类型名称
        supplyName: '', // 供应商名称
        supplyUuid: '', // 供应商Uuid
        supplyNo: '', // 供应商编码
        appliedArea: '', // 使用区域–JSON
        appliedAreaName: '', // 使用区域
        expireDate: '', // 过期时间
        fileList: [],
        imageList: [],
        enable: '1', // 是否启用
        note: '' // 说明--介绍
      },
      formDataRules: {
        qualificationName: [{ required: true, message: ' ', trigger: 'blur' }]
      },
      dialogVisible: false,
      qualificationFileType: '', // 资质文件类型
    };
  },
  created () {
    this.getCityTree();
    this.quaTypeProductList();
    this.getPagerSupplierMainInfo();
  },
  mounted () {
    this.uploadFileList = this.$refs.uploadFile?.fileList;
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
      if (val && this.uuid) { this.baseGetInfoByUuid(); }
    },
  },
  computed: {
    modalTitle () {
      if (this.isView) return '资质查看'
      return '资质编辑'
    }
  },
  methods: {
    changeImageKey (imgArr) {
      this.defaultList = [];
      this.formData.imageList = [];

      imgArr.forEach((item) => {
        let obj = {
          ...item
        };

        if (typeof item.url === 'string') {
          obj.url = item.url;
        } else {
          obj.url = item.url.previewUrl;
        }
        this.defaultList.push(obj);
      });

      this.defaultList.forEach((item) => {
        let obj = {};
        if (item.response) {
          obj.attachmentType = '1';
          obj.qualificationUuid = this.uuid;
          obj.attachmentUrl = item.response.retData.fileKey
          this.formData.imageList.push(obj);
        } else {
          obj.attachmentType = '1';
          obj.qualificationUuid = this.uuid;
          obj.attachmentUrl = item.attachmentUrl
          this.formData.imageList.push(obj);
        }
      });
    },
    baseGetInfoByUuid () {
      let curBtnId = getBtnsId('编辑');
      sessionStorage.setItem('buttonId', curBtnId);
      // 开始请求列表
      this.rLoading = true;
      ApiRequest(
        this.requestApi.baseGetByUuid.url + '?uuid=' + this.uuid,
        this.requestApi.baseGetByUuid.type,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let retData = res.retData;
          this.supplierNo = retData.supplyNo;
          this.formData = {
            qualificationName: retData.qualificationName, // 资质名称
            examineCate: retData.examineCate.toString(), // 检验类型 默认 1 全检
            original: retData.original, // 是否原件
            qualificationCate: retData.qualificationCate, // 资质类型
            qualificationCateName: retData.qualificationCateName,
            supplyName: retData.supplyName, // 供应商名称
            supplyUuid: retData.supplyUuid, // 供应商Uuid
            appliedArea: retData.appliedArea, // 使用区域–JSON
            supplyNo: retData.supplyNo,
            appliedAreaName: retData.appliedAreaName,
            expireDate: retData.expireDate, // 过期时间
            annex: retData.annex, // 附件地址
            fileList: retData.fileList, // 附件地址
            imageList: retData.imageList,
            enable: retData.enable ? '1' : '2', // 是否启用
            note: retData.note // 说明--介绍
          };
          this.defaultList = this.formData.imageList.reduce((value, item) => {
            value.push({ ...item, url: item.previewUrl, name: '' });
            return value;
          }, []);
          this.uploadFileList = retData.fileList.reduce((value, item) => {
            value.push({ name: item.attachmentUrl, url: item.previewUrl });
            return value;
          }, []);
          this.qualificationFileType = this.getQualificationFileType(); // 相关方法内容在fileMixins中
          this.$forceUpdate();
        }
        this.rLoading = false;
      });
    },
    searchBySupplierFun (type) {
      if (type === '0') {
        this.supplierName = '';
        this.supplierNo = '';
      } else {
        this.getPagerSupplierMainInfo();
      }
    },
    // 获取供应商列表
    getPagerSupplierMainInfo () {
      let searchParam = [];
      searchParam.push({ name: 'supplierName', value: this.supplierName });
      searchParam.push({ name: 'supplierName_q', value: 'Like' });
      searchParam.push({ name: 'supplierNo', value: this.supplierNo });
      searchParam.push({ name: 'supplierNo_q', value: 'EQ' });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        isAuth: 1,
        sortName: '',
        sortType: ''
      };
      let curBtnId = getBtnsId('编辑');
      sessionStorage.setItem('buttonId', curBtnId);
      // 开始请求列表
      ApiRequest(
        this.requestApi.getPagerSupplierMainInfo.url,
        this.requestApi.getPagerSupplierMainInfo.type,
        data,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          this.supplierMainData = res.retData.results;
          this.totalNum = res.retData.totalNum;
          // this.supplierNo = res.retData.supplierNo
        }
      });
    },
    // 获取资质类型
    quaTypeProductList () {
      let data = {};
      let curBtnId = getBtnsId('编辑');
      sessionStorage.setItem('buttonId', curBtnId);
      // 开始请求列表
      ApiRequest(
        this.requestApi.quaTypeProductList.url,
        this.requestApi.quaTypeProductList.type,
        data,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          this.quaTypeProductData = res.retData;
        }
      });
    },
    // 附件预览
    onPreView (url) {
      if (url.url) {
        window.open(url.url);
      } else {
        window.open(url.response.retData.previewUrl);
      }
    },
    // 选择供货商
    selectSupplier (row) {
      this.formData.supplyName = row.supplierName;
      this.formData.supplyUuid = row.supplierId;
      this.formData.supplyNo = row.supplierNo;
      this.supplierMainModel = false;

      this.$forceUpdate();
    },
    // 单选监听
    radioChange (data) {
      this.quaTypeProductData.forEach((element) => {
        if (data === element.quaTypeNo) {
          this.formData.qualificationCateName = element.quaTypeName;
        }
      });
    },
    changeStatTime (val) {
      this.formData.expireDate = val;
    },
    handleFileSuccess (res, file) {
      this.uploadBtnLoading = false;
      if (res) {
        const { retStatus, retData } = res
        if (retStatus == 1) {
          const { fileKey, previewUrl } = retData
          const fileObj = {
            previewUrl,
            attachmentUrl: fileKey,
            attachmentType: '2',
            qualificationUuid: this.uuid
          }
          this.formData.fileList.push(fileObj);
        } else {
          this.uploadFileList = [];
          this.$message.error('上传失败');
        }
      }
    },
    handleFileError (res, file) {
      this.uploadBtnLoading = false;
    },
    // 上传文件不能超100M
    handleMaxSize (file) {
      this.uploadBtnLoading = false;
      this.$message.error('上传文件大小不能超过100M');
    },
    handleBeforeFileUpload () {
      this.uploadBtnLoading = true;
      const check = this.formData.fileList.length < 1;
      if (!check) {
        this.uploadBtnLoading = false;
        this.$message.error('上传文件达到最大限制');
      }
      return check;
    },
    handleRemoveFile (file, fileList) {
      this.formData.fileList = []
    },
    formatError () {
      this.$Message.warning('文件格式错误,请上传pdf文件');
    },
    // 城市选择
    checkCityChange () {
      let sdata = this.$refs.cityTree.getCheckedNodes();

      this.formData.appliedArea = '';
      this.formData.appliedAreaName = '';
      sdata.forEach((item) => {
        if (item.children == undefined) {
          this.formData.appliedArea += item.code + ',';
          this.formData.appliedAreaName += item.title + ',';
        }
      });
      this.formData.appliedArea = this.formData.appliedArea.slice(
        0,
        this.formData.appliedArea.length - 1
      );
      this.formData.appliedAreaName = this.formData.appliedAreaName.slice(
        0,
        this.formData.appliedAreaName.length - 1
      );
    },
    // 获取城市树
    getCityTree () {
      let data = {};
      // let curBtnId = getBtnsId('编辑')
      // sessionStorage.setItem('buttonId', curBtnId)
      // 开始请求列表
      ApiRequest(
        this.requestApi.getCityTree.url,
        this.requestApi.getCityTree.type,
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          this.treeCityData = cityTreeDataUtils(res.retData);
          let treeCityDataall = [];
          this.treeCityData.forEach((item) => {
            let obj = {};
            obj.checked = item.checked;
            obj.code = item.code;
            obj.expand = item.expand;
            obj.nodeKey = item.nodeKey;
            obj.position = item.position;
            obj.title = item.title;
            treeCityDataall.push(obj);
          });
          this.treeCityData = [
            {
              title: '全选',
              expand: true,
              children: treeCityDataall
            }
          ];
          let appliedArea = this.formData.appliedArea.split(',');

          this.treeCityData[0].children.forEach((item) => {
            appliedArea.forEach((otem) => {
              if (item.code == otem) {
                item.checked = true;
              }
            });
          });
        }
      });
    },
    // 打开可售区域
    salableAreaHandle () {
      this.modal1 = true;

      if (this.cityUuids.length > 0) {
        this.cityUuids.forEach((item) => {
          let itemArr = item.split('-');
          for (let i = 0; i < this.salableAreaData.length; i++) {
            let fData = this.salableAreaData[i];
            if (fData.value === itemArr[0]) {
              if (itemArr[1] === 'ALL') {
                fData.checked = true;
                fData.children.forEach((obj) => {
                  obj.checked = true;
                });
              } else {
                fData.children.forEach((obj) => {
                  if (obj.value === itemArr[1]) {
                    obj.checked = true;
                  }
                });
              }
              return;
            }
          }
        });
      }
      this.areaDrawerShow = true;
    },
    // 商品详情图片
    changeDetailImage (imgArr) {},
    /* 必填校验方法 */
    judgeMandatoryFunc (formData) {
      if (!formData) { return false }
      const mandatoryList = [
        {
          key: 'qualificationName',
          label: '资质名称'
        },
        {
          key: 'examineCate',
          label: '检验类型'
        },
        {
          key: 'qualificationCate',
          label: '资质类型'
        },
        {
          key: 'supplyName',
          label: '供应商'
        },
        {
          key: 'appliedArea',
          label: '使用区域'
        },
        {
          key: 'expireDate',
          label: '过期时间'
        },
      ]
      let mandatoryStr = '';
      for (var i = 0; i < mandatoryList.length; i++) {
        if (!formData[mandatoryList[i].key] && formData[mandatoryList[i].key] !== 0) {
          mandatoryStr = `${mandatoryList[i].label}不能为空!`
          break;
        }
      }
      return mandatoryStr;
    },
    handleCloseDialog () {
      this.$emit('update:visible', false);
    },
    handleOk () {
      const mandatoryStr = this.judgeMandatoryFunc(this.formData);
      if (mandatoryStr) { return this.$Message.warning(mandatoryStr) }
      if (this.isEmptyFileByType()) { // isEmptyFileByType在fileMixins中
        return this.$Message.warning('上传附件与上传图片需至少上传一处，请上传后重试！');
      }
      this.toRelease(this.formData);
      this.$emit('update:visible', false);
    },
    toRelease (formData) {
      this.formData.expireDate = this.changeDate(this.formData.expireDate);
      this.formData.uuid = this.uuid;
      let copyData = Object.assign({}, formData);
      let curBtnId = getBtnsId('编辑');
      sessionStorage.setItem('buttonId', curBtnId);
      // 开始请求列表
      this.rLoading = true;
      ApiRequest(
        this.requestApi.baseUpdate.url,
        this.requestApi.baseUpdate.type,
        copyData
      )
        .then((res) => {
          this.rLoading = false;
          if (res.retStatus === '1') {
            this.$Message.success('修改资质成功!');
          }
        })
        .catch(() => {
          this.rLoading = false;
        });
    },
    // 时区日期格式转换(TZ)
    changeDate (myData) {
      var date1 = new Date(myData).toJSON();
      var date = new Date(+new Date(date1) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '');
      return date;
    },
    searcheSupply () {
      this.supplierMainModel = true;
    },
    handleTablaeSelect (data) {},
    handleSelectAll (data) {},
    handleSelectAllCancel (data) {},
    changePage (e) {
      this.nowPage = e;
      this.getPagerSupplierMainInfo();
    },

    changePageSize (e) {
      this.pageShow = e;
      this.getPagerSupplierMainInfo();
    }
  }
};
</script>
<style lang="less" scoped>
.mt-10 {
  margin-bottom: 10px;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
